#include "ftcpsocket.h"

FTcpSocket::FTcpSocket(QTcpSocket *pSocket)
    : FNetProtocol(), m_pTcpSocket(pSocket ? pSocket : (new QTcpSocket(nullptr)))
{
    m_pTcpSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
    qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
    connect(m_pTcpSocket, SIGNAL(readyRead()), this, SLOT(SlotReadyRead()));
    connect(m_pTcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SIGNAL(StateChanged(QAbstractSocket::SocketState)));
    connect(m_pTcpSocket, SIGNAL(disconnected()), this, SIGNAL(Disconnected()));
}

FTcpSocket::~FTcpSocket()
{
    if( nullptr != m_pTcpSocket)
    {
        m_pTcpSocket->deleteLater();
    }
}

bool FTcpSocket::Flush()
{
    if( nullptr != m_pTcpSocket)
    {
         return m_pTcpSocket->flush();
    }
    return false;
}

bool FTcpSocket::WaitForBytesWritten(int msecs)
{
    if( nullptr != m_pTcpSocket)
    {
         return m_pTcpSocket->waitForBytesWritten(msecs);
    }
    return false;
}

bool FTcpSocket::WaitForReadyRead(int msecs)
{
    if( nullptr != m_pTcpSocket)
    {
         return m_pTcpSocket->waitForReadyRead(msecs);
    }
    return false;
}

qint64 FTcpSocket::Write(const QByteArray &byteArray)
{
    QByteArray bytePack;
    if( nullptr != m_pTcpSocket && 0 < NetPackFill(byteArray, bytePack))
    {
//        qDebug()<<"Write<<<<<<<<<<<<<<<<<<<<<<<<<<"<<bytePack.toHex();
        return m_pTcpSocket->write(bytePack);
    }
    return 0;
}

void FTcpSocket::ConnectToHost(const QHostAddress &address, quint16 port, QIODevice::OpenMode openMode)
{
    if( nullptr != m_pTcpSocket)
    {
        return m_pTcpSocket->connectToHost(address, port, openMode);
    }

}

bool FTcpSocket::WaitForConnected(int msecs)
{
    if( nullptr != m_pTcpSocket)
    {
        return m_pTcpSocket->waitForConnected(msecs);
    }
    return false;
}

bool FTcpSocket::WaitForDisconnected(int msecs)
{
    if( nullptr != m_pTcpSocket)
    {
        return m_pTcpSocket->waitForDisconnected(msecs);
    }
   return false;
}

void FTcpSocket::DisconnectFromHost()
{
    if( nullptr != m_pTcpSocket)
    {
        return m_pTcpSocket->disconnectFromHost();
    }
}

QHostAddress FTcpSocket::PeerAddress() const
{
    return m_pTcpSocket->peerAddress();
}

QAbstractSocket::SocketState FTcpSocket::State() const
{
    return m_pTcpSocket->state();
}

void FTcpSocket::SlotReadyRead()
{
    QByteArray byteBuf = m_pTcpSocket->readAll();

    if(byteBuf.size() > 0)
    {
        NetUnPack(byteBuf);
    }
}

qint32 FTcpSocket::RecvPackData(QByteArray &bytePack)
{
    if( bytePack.size() > 0 )
    {
        emit SigPackData(bytePack);
    }

    return 0;
}
